package com.topcent.tioxyc.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.Fukuandan;
import com.topcent.tioxyc.pojo.vo.NotesVO;
import com.topcent.tioxyc.pojo.vo.SaleTextResult;
import com.topcent.tioxyc.pojo.vo.SaleTextVO;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 陈百万
 * @date: 2025/9/18 10:59
 * @Description: 采购订单销售备注
 */
@Slf4j
@RestController
public class AddSalesToChangeController {

    private static final String DATA_CREATE = "data_create";

    private static final String SECRET = "KPIfb04KeXBOWkj3m9xDqKV9";

    @PostMapping("/addSalesToChange")
    public String addSalesToChange(@RequestParam("nonce") String nonce,
                               @RequestParam("timestamp") String timestamp,
                               @RequestHeader("x-jdy-signature") String signature,
                               @RequestBody String payload) {
        if (!validateSignature(nonce, payload, timestamp, signature)) {
            return "fail";
        }
        // 在这里处理消息
        handleData(payload);

        return "success";
    }

    private void handleData(String payload) {
        // 在这里处理推送来的数据
        JSONObject payloadJSON = JSONUtil.parseObj(payload);
        String op = payloadJSON.getStr("op");
        String data = payloadJSON.getStr("data");

        if (DATA_CREATE.equals(op)) {
            createChange(data);
        }

    }

    // 处理数据
    private void createChange(String datas) {
        Header[] headers = ConnmeUtils.createHeaders();
        NotesVO notesVO = JSONUtil.toBean(datas, NotesVO.class);

        String pNo = notesVO.get_widget_1758161813154(); // 采购订单号

        String appId = "6690c7633df0f4b90b4ef551";
        String entryId = "6690c891b1ffef3310d1b90d";

        // 通过采购订单获取备注信息
        List<SaleTextVO> saleTextVOList = new ArrayList<>();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", appId);
        parameter.put("entry_id", entryId);

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "bill_number");
        cond.put("type", "text");
        cond.put("method", "eq");
        List<String> values = new ArrayList<>();
        values.add(pNo);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<SaleTextVO> list = JSONUtil.toList(objects, SaleTextVO.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            saleTextVOList.addAll(list);
        } while (fale);

        SaleTextVO first = saleTextVOList.getFirst(); // 采购订单

        SaleTextResult result = new SaleTextResult();
        result.set_id(first.get_id());
        result.set_widget_1754385003661(first.getPurchase_orders().getFirst().get_widget_1737440340378());
        if(StringUtils.isNotBlank(result.get_widget_1754385003661())){
            // 更新数据
            Map<String, Object> parameterInster = new HashMap<>();
            parameterInster.put("app_id", appId);
            parameterInster.put("entry_id", entryId);
            parameterInster.put("is_start_trigger", "true");
            parameterInster.put("data_id", result.get_id());
            result.set_id(null);
            parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(result));
            String jsonSalee = JSONUtil.toJsonStr(parameterInster);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
        }
    }

    private boolean validateSignature(String nonce, String payload, String timestamp, String signature) {
        String calculatedSignature = getSignature(nonce, payload, timestamp);
        return calculatedSignature.equals(signature);
    }

    private String getSignature(String nonce, String payload, String timestamp) {
        return DigestUtils.sha1Hex(nonce + ":" + payload + ":" + AddSalesToChangeController.SECRET + ":" + timestamp);
    }
}
